package com.graduation.lastproject.util.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.graduation.lastproject.service.hotellist.HotellistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Pay {
    private static Logger logger = LoggerFactory.getLogger(Pay.class);

    @Autowired
    private HotellistService hotellistService;


    @RequestMapping(value = "/pay")
    public void payController(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

      /*
          入住人姓名 电话
      * */
        String passback=request.getParameter("realname")+","+request.getParameter("phone")+","+
                request.getParameter("hotelId")+","+request.getParameter("hotelRoom")+","+request.getParameter("userPhone");


        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("UTF-8"),"UTF-8");
     /*   //商品描述，可空
        String body = new String(request.getParameter("").getBytes("UTF-8"),"UTF-8");*/
       /*公用回传参数*/
       String passback_params=new String(passback.getBytes("utf-8"),"utf-8");

     /*
     数据更新一波：
     * */

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"passback_params\":\""+ passback_params +"\","
                + "\"timeout_express\":\"10m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping(value = "returnPay",method = RequestMethod.POST)
    @ResponseBody
    public Object aliRefund(HttpServletRequest request1) {
        Map<String,Object> map = parameters(request1);

        //获得初始化的AlipayClient
        int price=Integer.parseInt(map.get("total_price").toString()); //价格
        Map<String,Object> result=new HashMap<>();
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + map.get("out_trade_no").toString() + "\"," +
                    "\"refund_amount\":\"" + price + "\"" +
                    "  }");

            AlipayTradeRefundResponse response = alipayClient.execute(request);
            logger.info("返回结果：" + response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("支付宝退款>>退款失败: 调用支付宝接口出现异常");
            result.put("msg","退款失败");
        }
        map.put("trade_state",2);
        int hotelRoomType;
                if(map.get("hotelRoom").toString().indexOf("大床房") != -1){
                    hotelRoomType=1;
                } else if(map.get("hotelRoom").toString().indexOf("双人房") != -1){
                    hotelRoomType=2;
                }else if(map.get("hotelRoom").toString().indexOf("商务房") != -1){
                    hotelRoomType=3;
                }else {
                    hotelRoomType=4;
                }
        //用户积分减少
        hotellistService.updateUserIntegral(map.get("userPhone"),map.get("total_price"));
        //房间库存增加
        hotellistService.updataHotel(map.get("hotelId").toString(),hotelRoomType);
        int i=hotellistService.updataBookOrderInfo(map);
        result.put("msg",i == 1?"成功":"");
        return result;
    }



    /**
     * 支付宝同步通知页面,成功返回首页
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(Model model, HttpServletRequest request, HttpServletRequest response) throws Exception {
        return "home/withMe";//成功返回首页
    }
/*
        logger.info("支付成功, 进入同步通知接口...");

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额，这里获取到三个参数就可以了，后面逻辑代码自己创作
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            int result=0;
            //这里根据自身的业务写代码，我这里删掉了

            if(result==0){
                model.addAttribute("resultinfo","更新订单失败！请业务员联系后台管理员！");
            }else {
                model.addAttribute("resultinfo","出租工具成功！");
            }
            logger.info("********************** 支付成功(支付宝同步通知) **********************");
            logger.info("* 订单号: {}", out_trade_no);
            logger.info("* 支付宝交易号: {}", trade_no);
            logger.info("* 实付金额: {}", total_amount);
            logger.info("***************************************************************");
        }else {
            logger.info("支付, 验签失败...");
        }*/


    /**
     * 支付宝异步 通知页面
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayNotifyNotice" ,method = RequestMethod.POST)
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        logger.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
           // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //交易创建时间
            String gmt_create=new String(request.getParameter("gmt_create").getBytes("iso-8859-1"),"utf-8");
            //交易付款时间
            String gmt_payment=new String(request.getParameter("gmt_payment").getBytes("iso-8859-1"),"utf-8");
            //回传参数处理
            String getparams=new String(request.getParameter("passback_params").getBytes("utf-8"),"utf-8");
            String realname=getparams.split(",")[0];
            String phone=getparams.split(",")[1];
            String hotelId=getparams.split(",")[2];
            String hotelRoom=getparams.split(",")[3];
            String userPhone=getparams.split(",")[4];
            /*String uservipScore=getparams.split(",")[5];
            String userIntegral=getparams.split(",")[6];*/

            /*4.1 更新用户表vipscore 和积分*/
            Map<String,Object> usermap=new HashMap<>();
            usermap.put("userPhone",userPhone);
            usermap.put("total_amount",total_amount);
           /* usermap.put("uservipScore",uservipScore);
            usermap.put("userIntegral",userIntegral);*/


            /*更新订单表的字段*/
            Map<String,Object> map=new HashMap<>();
            map.put("bookuser",realname);
            map.put("book_user_phone",phone);
            map.put("userPhone",userPhone);
            map.put("out_trade_no",out_trade_no);
            map.put("gmt_create",gmt_create);
            map.put("gmt_payment",gmt_payment);
            map.put("total_amount",total_amount);
            map.put("trade_state",1);

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                /*支付成功首先对酒店房间库存进行操作*/
                hotellistService.updataHotelNumInfo(hotelId,hotelRoom);
                /*个人积分更新*/
                hotellistService.updataUserInfo(usermap);
                /*然后对订单表进行更新*/
                int result=hotellistService.updataBookOrderInfo(map);

                if(result==0){
                    logger.info("result","更新订单失败！");
                }else {
                    logger.info("result","更新订单成功！");
                }

                logger.info("********************** 支付成功(支付宝异步通知) **********************");
                logger.info("* 订单号: {}", out_trade_no);
                logger.info("* 支付宝交易号: {}", trade_no);
                logger.info("* 实付金额: {}", total_amount);
                logger.info("***************************************************************");
            }
            logger.info("支付成功...");
        }else {//验证失败
            logger.info("支付, 验签失败...");
        }
        return "success";
    }

    /** request转map */
    private final static Map<String, Object> parameters(HttpServletRequest request) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (request != null) {
            Enumeration<String> keys = request.getParameterNames();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                try {
                    parameters.put(key, request.getParameter(key));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return parameters;
    }


}

